package Course;


import java.sql.*;

public class Course implements CourseDAO {

    String url = "jdbc:sqlserver://localhost:1433;databaseName=Student_Grade_Management_System;trustServerCertificate=true";
    String user = "ysy";
    String password = "051018";

    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    @Override
    public void insertCourse(int id, String name, double a,double b) {
        String query = "INSERT INTO 课程 VALUES (?,?,?,?)";

        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setInt(1, id);
            ps.setString(2, name);
            ps.setDouble(3, a);
            ps.setDouble(4, b);

            ps.executeUpdate();
            System.out.println("插入成功！");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateCourse(int id, String name, double a,double b) {
        String query = "UPDATE 课程 SET  课程名 = ?, 平时成绩占比 = ?,考试成绩占比=? WHERE 课程编号 = ?";

        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {


            ps.setString(1, name);
            ps.setDouble(2, a);
            ps.setDouble(3, b);
            ps.setInt(4, id);
            ps.executeUpdate();
            System.out.println("课程信息更新成功！");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void deleteCourse(int id) {
        String query = "DELETE FROM 课程 WHERE 课程编号 = ?";

        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setInt(1, id);
            ps.executeUpdate();
            System.out.println("课程删除成功！");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getCourse() {
        String sql = "select * from 课程";
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement()) {
             ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            // 6. 打印列名
            for (int i = 1; i <= columnCount; i++) {
                System.out.print(metaData.getColumnName(i) + "\t");
            }
            System.out.println(); // 换行

            // 7. 打印数据
            while (rs.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    String value = rs.getString(i);
                    System.out.print(value + "\t");
                }
                System.out.println(); // 每行数据输出后换行
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
